from django.http import JsonResponse
from django.views import View
from QQLoginTool.QQtool import OAuthQQ

from apps.oauth.models import OAuthQQUser
from apps.users.models import User
from apps.oauth.utils import Serializer_openid, UnSerializer_openid
from utils.transformJson import TransformJson
from youshugou import settings
from django.contrib.auth import login


class QQLoginTool(View):
    def get(self, request):
        qq = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                     client_secret=settings.QQ_CLIENT_SECRET,
                     redirect_uri=settings.QQ_REDIRECT_URI,
                     state='XX')
        qq_url = qq.get_qq_url()
        return JsonResponse({'code': 0, 'errmsg': 'ok', 'login_url': qq_url})


class OauthQQview(View):
    def get(self, request):
        code = request.GET.get('code')
        if code is None:
            return JsonResponse({'code': 400, 'errmsg': '参数不全'})
        qq = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                     client_secret=settings.QQ_CLIENT_SECRET,
                     redirect_uri=settings.QQ_REDIRECT_URI,
                     state='XX')
        # 获取qq token
        token = qq.get_access_token(code)
        # openid是用户在此网站的唯一id
        openid = qq.get_open_id(token)
        # 加密数据
        try:
            qquser = OAuthQQUser.objects.get(openid=openid)
        except OAuthQQUser.DoesNotExist:
            # 不存在，需要绑定
            access_token = Serializer_openid(openid)
            response = JsonResponse({'code': 400, 'access_token': access_token})
            return response
        else:
            # 存在，进行跳转到首页
            login(request, qquser.user)
            response = JsonResponse({'code': 0, 'errmsg': 'ok'})
            response.set_cookie('username', qquser.user.username)
            return response

    def post(self, request):
        # 接收请求,获取请求参数
        data = TransformJson(request)
        password = data.get('password')
        mobile = data.get('mobile')
        sms_code = data.get('sms_code')
        openid = data.get('access_token')
        # ****进行验证

        # 根据手机号进行用户信息的查询
        try:
            user = User.objects.get(mobile=mobile)
        except User.DoesNotExist:
            # 手机号不存在
            user = User.objects.create_user(username=mobile, mobile=mobile, password=password)
        else:
            # 手机号存在
            if not user.check_password(password):
                return JsonResponse({'code': 400, 'errmsg': '账号或密码不正确'})
        if UnSerializer_openid(openid) is None:
            return JsonResponse({'code': 400, 'errmsg': 'code错误'})
        access_token = UnSerializer_openid(openid)
        OAuthQQUser.objects.create(user=user, openid=access_token)
        # 状态保持
        login(request, user)
        response = JsonResponse({'code': 0, 'errmsg': 'ok'})
        response.set_cookie('username', user.username)
        return response

    # 返回响应
    pass
